package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.unit.UserContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CrmRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RoleMapper RoleMapper;

    //将Spring容器凭证匹配器bean注入到AuthorizingRealm
    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    //用户登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Object credentials = token.getCredentials();
        Employee employee = employeeMapper.selectByName(username);
        if (employee == null) {
            //登录失败
            return null;
        }
        //检查员工是否被禁用
        if (employee.isStatus() == false) {
            //抛出账号被禁用
            throw new DisabledAccountException();
        }

        //使用用户名作为加密的盐
        ByteSource salt = ByteSource.Util.bytes(employee.getName());
        //用户信息  用户密码   盐    realm名
        return new SimpleAuthenticationInfo(employee, employee.getPassword(), salt, this.getName());
    }

    //用户权限认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //创建用户的授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录用户信息
        Employee employee = UserContext.getUser();
        //判断用户是否超级管理员
        if (employee.isAdmin()) {
            //给管理员赋予ADMIN角色
            info.addRole("ADMIN");
            //给管理员赋予全部权限
            info.addStringPermission("*:*");
        } else {
            //查询用户的所有角色编码
            List<Role> roles = RoleMapper.selectByEmpId(employee.getId());
            for (Role role : roles) {
                info.addRole(role.getSn());
            }
            //根据用户id查询权限
            List<String> expressions = employeeMapper.selectExpressionById(employee.getId());
            info.addStringPermissions(expressions);
        }
        return info;
    }


}
